<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-top">
        <div class="login-header">
          <div class="login-title">
            <h2>货物监控系统</h2>
            <p>Smart Shipment Monitor</p>
          </div>
        </div>
        <div class="login-desc">
          欢迎使用，请登录
        </div>
      </div>

      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form">
        <el-form-item prop="username">
          <el-input
            ref="usernameRef"
            v-model="loginForm.username"
            placeholder="用户名"
            type="text"
            tabindex="1"
            size="large"
            clearable
            :prefix-icon="User"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            ref="passwordRef"
            v-model="loginForm.password"
            placeholder="密码"
            :type="passwordVisible ? 'text' : 'password'"
            tabindex="2"
            size="large"
            :prefix-icon="Lock"
            @keyup.enter="handleLogin"
          >
            <template #suffix>
              <el-icon class="el-input__icon cursor-pointer" @click="passwordVisible = !passwordVisible">
                <component :is="passwordVisible ? 'View' : 'Hide'" />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-button :loading="loading" type="primary" class="login-button" @click="handleLogin">
          登录系统
        </el-button>
      </el-form>

      <div class="login-footer">
        <p>Copyright © {{ currentYear }} 货物监控系统</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { User, Lock, View, Hide } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 表单引用
const loginFormRef = ref(null)
const usernameRef = ref(null)
const passwordRef = ref(null)

// 表单数据
const loginForm = reactive({
  username: 'admin',
  password: 'admin123'
})

// 表单验证规则
const loginRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

// 状态
const loading = ref(false)
const passwordVisible = ref(false)
const rememberMe = ref(false)
const redirect = computed(() => route.query.redirect || '/')
const currentYear = computed(() => new Date().getFullYear())

// 登录处理
const handleLogin = () => {
  loginFormRef.value.validate(valid => {
    if (valid) {
      loading.value = true
      userStore.login(loginForm)
        .then(() => {
          ElMessage.success('登录成功')
          
          // 从本地存储获取重定向路径
          const savedRedirect = localStorage.getItem('redirectPath')
          if (savedRedirect) {
            localStorage.removeItem('redirectPath') // 使用后删除
            // 如果有保存的路径，优先使用
            if (savedRedirect.startsWith('/#/')) {
              // 只获取hash部分，去掉/#前缀
              router.push({ path: savedRedirect.substring(2) })
            } else {
              router.push({ path: redirect.value })
            }
          } else {
            // 否则使用URL参数中的redirect
            router.push({ path: redirect.value })
          }
        })
        .catch(error => {
          console.error('登录失败:', error)
          // ElMessage.error('用户名或密码错误')
        })
        .finally(() => {
          loading.value = false
        })
    }
  })
}

onMounted(() => {
  // 如果已经登录，直接跳转到首页
  if (userStore.token) {
    // 检查是否有重定向路径
    const savedRedirect = localStorage.getItem('redirectPath')
    if (savedRedirect) {
      localStorage.removeItem('redirectPath') // 使用后删除
      if (savedRedirect.startsWith('/#/')) {
        // 只获取hash部分，去掉/#前缀
        router.push({ path: savedRedirect.substring(2) })
      } else {
        router.push({ path: redirect.value })
      }
    } else {
      router.push({ path: redirect.value })
    }
  }
  
  // 自动聚焦用户名输入框
  if (usernameRef.value) {
    usernameRef.value.focus()
  }
})
</script>

<style lang="scss" scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(225deg, #f5f7fa 0%, #c3cfe2 100%);
  overflow: hidden;
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 50%;
    background: linear-gradient(to right, rgba(64, 158, 255, 0.1), rgba(64, 158, 255, 0.05));
    transform: skewY(-3deg);
    transform-origin: top right;
  }
}

.login-card {
  width: 420px;
  padding: 40px 35px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
  z-index: 2;
  animation: fadeInUp 0.5s ease;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-top {
  text-align: center;
  margin-bottom: 30px;
}

.login-header {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
}

.login-logo {
  height: 40px;
  margin-right: 12px;
}

.login-title {
  text-align: left;
  
  h2 {
    margin: 0;
    font-size: 22px;
    font-weight: 600;
    color: #333;
  }
  
  p {
    margin: 5px 0 0;
    font-size: 14px;
    color: #909399;
  }
}

.login-desc {
  font-size: 16px;
  color: #606266;
  margin-top: 12px;
}

.login-form {
  margin-bottom: 20px;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.login-button {
  width: 100%;
  height: 44px;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 1px;
}

.login-footer {
  text-align: center;
  color: #909399;
  font-size: 13px;
  margin-top: 30px;
  p {
    margin: 0;
  }
}

.cursor-pointer {
  cursor: pointer;
}

@media (max-width: 576px) {
  .login-card {
    width: 90%;
    padding: 30px 20px;
  }
}
</style>